<template>
    <el-select placeholder="请选择/Please Choose" v-model="internalValue" :multiple="multiple" collapse-tags
        @change="handleChange" clearable>
        <el-option v-for="(item, index) in items" :key="item.id" :label="`${item.bh}-${item.mc}`"  :value="item.id">
            {{ item.bh }}-{{ item.mc }}
        </el-option>
    </el-select>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, watch } from 'vue'
import request from '/@/utils/request'

export default defineComponent({
    name: 'VpWarehouseSelect',
    emits: ['update:modelValue', 'selected', 'selected-items'],
    props: {
        // 现在modelValue只存储ID（单个或数组）
        modelValue: {
            type: [String, Number, Array, null],
            default: null
        },
        multiple: {
            type: Boolean,
            default: false,
        },
        lbList: {
            type: Array as () => any[],
            default: () => [],
        },
        jdidList: {
            type: Array as () => any[],
            default: () => [],
        },
    },
    setup(props, context) {
        const state = reactive({
            loading: false,
            items: [] as any[],
            internalValue: props.modelValue // 内部值，存储ID
        })

        // 监听外部v-model的变化，同步到组件内部
        watch(
            () => props.modelValue,
            (newVal) => {
                state.internalValue = newVal
            }
        )

        // 监听内部值变化，同步到外部v-model
        watch(
            () => state.internalValue,
            (newVal) => {
                // 触发v-model更新事件（传递ID）
                context.emit("update:modelValue", newVal);
                // 同时传递ID给原有事件
                context.emit("selected", newVal);
                // 新增事件，传递完整的选中对象
                context.emit("selected-items", getSelectedItems(newVal));
            }
        )

        // 根据ID获取选中的完整对象
        const getSelectedItems = (ids: any) => {
            if (!ids) return props.multiple ? [] : null;

            if (props.multiple) {
                return (ids as any[]).map(id => {
                    return state.items.find((item: any) => item.id === id) || null;
                }).filter(Boolean);
            } else {
                return state.items.find((item: any) => item.id === ids) || null;
            }
        }

        const loadData = () => {
            state.loading = true;
            request.get('/masterData/warehouse/list', {
                params: {
                    jdidList: props.jdidList || [],
                    lbList: props.lbList || [],
                }
            }).then(res => {
                state.items = res?.data || [];
            }).finally(() => {
                state.loading = false;
            });
        }

        onMounted(() => {
            loadData();
        })

        const handleChange = (data: any) => {
            state.internalValue = data;
        }

        return {
            ...toRefs(state),
            ...toRefs(props),
            handleChange,
        }
    }
})
</script>
